package com.newway.wechat.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.newway.common.MyPages;
import com.newway.common.Result;
import com.newway.util.QRCodeUtil;
import com.newway.wechat.context.UserInfoContext;
import com.newway.wechat.dto.SignInDto;
import com.newway.wechat.dto.SignSavaDto;
import com.newway.wechat.entity.sign.SignBlackWhiteListEntity;
import com.newway.wechat.entity.sign.SignDataEntity;
import com.newway.wechat.entity.sign.SignLocation;
import com.newway.wechat.entity.sign.SignRecordEntity;
import com.newway.wechat.enums.BusinessTypeEnum;
import com.newway.wechat.enums.SignStatusEnum;
import com.newway.wechat.enums.SignTypeEnum;
import com.newway.wechat.mapper.SignBlackAndWhiteMapper;
import com.newway.wechat.mapper.SignDataMapper;
import com.newway.wechat.mapper.SignRecordMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/wechat/sign")
public class SignController {

    @Resource
    SignDataMapper signDataMapper;

    @Resource
    SignRecordMapper signRecordMapper;

    @Resource
    SignBlackAndWhiteMapper signBlackAndWhiteMapper;

    /**
     * 获取首页签到数据
     * @param signDataEntity
     * @return
     */
    @GetMapping("/dataList")
    public Result getSignList(SignDataEntity signDataEntity){
        signDataEntity.getParams().put("pageNum",(signDataEntity.getPageNum()-1)* signDataEntity.getPageSize());
        MyPages<SignDataEntity> selectPage = new MyPages<>();
        long totals = signDataMapper.dataListCount(signDataEntity, UserInfoContext.getUserInfo());
        if(totals>0){
            List<SignDataEntity> result = signDataMapper.dataList(signDataEntity, UserInfoContext.getUserInfo());
            selectPage.setTotal(totals);
            selectPage.setPages(totals%signDataEntity.getPageSize()==0?totals/signDataEntity.getPageSize():(totals/signDataEntity.getPageSize())+1);
            selectPage.setRecords(result);
        }
        return Result.success(selectPage);
    }

    /**
     *
     * @return
     */
    @GetMapping("/getPublished")
    public Result getNotPublishData(){
        QueryWrapper<SignDataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sign_publisher",UserInfoContext.getUserInfo().getId());
        queryWrapper.eq("sign_status","0");
        queryWrapper.in("sign_status", Arrays.asList("0","2"));
        queryWrapper.orderByAsc("sign_status");
        queryWrapper.orderByDesc("id");
        List<SignDataEntity> signDataEntities = signDataMapper.selectList(queryWrapper);
        return Result.success(signDataEntities);
    }

    /**
     * 签到新增
     * @param signSavaDto
     * @return
     */
    @PostMapping("/signAdd")
    public Result signDataAdd(@RequestBody SignSavaDto signSavaDto){
        System.out.println(signSavaDto.toString());
        String endTimeStr = signSavaDto.getEndTime().concat(":00:000");
        DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
        LocalDateTime endTime = LocalDateTime.parse(endTimeStr, originalFormatter);
        LocalDateTime startTime = LocalDateTime.now();
        if(endTime.isBefore(startTime)){
            return Result.fail("结束时间必须大于当前时间");
        }
        SignDataEntity signDataEntity = new SignDataEntity();
        signDataEntity.setSignTitle(signSavaDto.getSignTitle());
        signDataEntity.setSignType(signSavaDto.getSignType());
        signDataEntity.setSignAddress(signSavaDto.getSignAddress());
        signDataEntity.setStartTime(startTime);
        signDataEntity.setEndTime(endTime);
        signDataEntity.setSignRemark(signSavaDto.getSignRemark());
        signDataEntity.setCreateTime(startTime);
        signDataEntity.setSignPublisher(UserInfoContext.getUserInfo().getId());
        signDataEntity.setSignStatus(signSavaDto.getSignStatus());
        if(SignTypeEnum.GPS.code.equals(signSavaDto.getSignType())){
            SignLocation location = signSavaDto.getLocation();
            Integer range = signSavaDto.getRange();
            location.setRange(range);
            signDataEntity.setSignJson(JSON.toJSONString(location));
            signDataEntity.setSignAddress(location.getAddress());
        }
        signDataMapper.insert(signDataEntity);
        return Result.success(1);
    }


    /**
     * 待发布的数据转发布
     * @param id
     * @return
     */
    @GetMapping("/publish/{id}")
    public Result publish(@PathVariable("id") Long id){
        SignDataEntity signDataEntity = signDataMapper.selectById(id);
        if(signDataEntity==null){
            return Result.fail("当前数据不存在，请刷新重试");
        }
        if(SignStatusEnum.NEW.code.equals(signDataEntity.getSignStatus())){
            signDataEntity.setSignStatus(SignStatusEnum.PUBLISHED.code);
            signDataMapper.updateById(signDataEntity);
            return Result.success(null);
        }
        return Result.fail("数据错误，请刷新重试");
    }

    /**
     * 删除未发布数据
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public Result deleteSignData(@PathVariable("id") Long id){
        SignDataEntity signDataEntity = signDataMapper.selectById(id);
        if(signDataEntity==null){
            return Result.fail("当前数据不存在，请刷新重试");
        }
        if(SignStatusEnum.NEW.code.equals(signDataEntity.getSignStatus())){
            signDataMapper.deleteById(id);
            return Result.success(null);
        }
        return Result.fail("数据错误，请刷新重试");
    }


    /**
     * 用户签到
     * @param id
     * @return
     */
    @PostMapping("/signIn/{id}")
    public Result signIn(@PathVariable("id") Long id,@RequestBody SignInDto signInDto){
        SignDataEntity signDataEntity = signDataMapper.selectById(id);
        if(signDataEntity == null){
            return Result.fail("签到表不存在，请刷新重试");
        }
        if(!SignStatusEnum.PUBLISHED.code.equals(signDataEntity.getSignStatus())){
            return Result.fail("数据异常");
        }
        if(signDataEntity.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("签到已过期");
        }
        QueryWrapper<SignRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sign_id",id);
        queryWrapper.eq("sign_user_id",UserInfoContext.getUserInfo().getId());
        List<SignRecordEntity> signRecordEntities = signRecordMapper.selectList(queryWrapper);
        if(signRecordEntities.size()>0){
            return Result.fail("您已签到，不可重复签到!");
        }
        QueryWrapper<SignBlackWhiteListEntity> signBlackWhiteListEntityQueryWrapper = new QueryWrapper<>();
        signBlackWhiteListEntityQueryWrapper.eq("list_type","0");
        signBlackWhiteListEntityQueryWrapper.eq("sign_id",id);
        signBlackWhiteListEntityQueryWrapper.eq("sign_user_id",UserInfoContext.getUserInfo().getId());
        List<SignBlackWhiteListEntity> signBlackWhiteListEntities = signBlackAndWhiteMapper.selectList(signBlackWhiteListEntityQueryWrapper);
        if(signBlackWhiteListEntities.size()>0){
            return Result.fail("您不在本次签到列表中，无法签到");
        }
        SignRecordEntity signRecordEntity = new SignRecordEntity();
        signRecordEntity.setSignId(id);
        signRecordEntity.setSignTime(LocalDateTime.now());
        signRecordEntity.setSignUserId(UserInfoContext.getUserInfo().getId());
        signRecordEntity.setSignUserName(UserInfoContext.getUserInfo().getNickName());
        signRecordEntity.setSignDetails(signInDto.getDetails());
        signRecordMapper.insert(signRecordEntity);
        return Result.success(0);
    }

    /**
     * 将数据生成二维码
     * @param id
     * @return
     */
    @GetMapping("/jsonQr/{id}")
    public Result jsonQr(@PathVariable("id") Long id) throws Exception {
        // 1. 组装业务 JSON
        Map<String, Object> json = new HashMap<>();
        json.put("id", id);
        SignDataEntity signDataEntity = signDataMapper.selectById(id);
        if(signDataEntity == null){
            return Result.fail("无效的二维码");
        }
        if(!SignStatusEnum.PUBLISHED.code.equals(signDataEntity.getSignStatus())){
            return Result.fail("该二维码已失效");
        }
        json.put("signTyp",signDataEntity.getSignType());
        json.put("businessType", BusinessTypeEnum.SIGN_IN.code);
        json.put("toPath","/pages/sign/codeSign/codeSign?id="+id);
        String content = new ObjectMapper().writeValueAsString(json);
        String base64 = QRCodeUtil.generateQRCodeBase64(content);
        return Result.success(base64);
    }

    /**
     * 获取签到结果
     * @param id
     * @return
     */
    @GetMapping("/signResult/{id}")
    public Result signResult(@PathVariable("id") Long id){
        SignDataEntity signDataEntity = signDataMapper.selectById(id);
        if(signDataEntity == null){
            return Result.fail("无效数据，请刷新重试");
        }
        QueryWrapper<SignRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sign_id",id);
        queryWrapper.eq("sign_user_id",UserInfoContext.getUserInfo().getId());
        List<SignRecordEntity> signRecordEntities = signRecordMapper.selectList(queryWrapper);
        if(signRecordEntities.size()>0){
            Map<String,Object> result = new HashMap<>();
            result.put("signData",signDataEntity);
            result.put("signRecord",signRecordEntities.get(0));
            return Result.success(result);
        }
        return Result.success(null);
    }
}
